package com.bocai.grainshop.cart.config;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;

@Configuration
public class CartFeignInterceptor {

    //给远程feign请求在进入业务之前加上cookie
    @Bean("cartFeignServerInterceptor")
    public RequestInterceptor setRequestInterceptor(){
        return requestTemplate -> {
            //获取当前上下文的所有请求信息
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null){
                HttpServletRequest request = requestAttributes.getRequest();
                if(request != null){
                   requestTemplate.header("Cookie",request.getHeader("Cookie"));
                }
            }
        };
    }
}
